import React, { useState, useEffect } from "react";
import { ConfigProvider, theme as antdTheme } from "antd";
import { DragDropContext, DropResult } from "@hello-pangea/dnd";
import TodoList from "./components/TodoList";
import TodoForm from "./components/TodoForm";
import TodoFilter from "./components/TodoFilter";
import ThemeToggle from "./components/ThemeToggle";
import "./App.css";

export interface Todo {
  id: number;
  text: string;
  completed: boolean;
  priority: "low" | "medium" | "high";
  dueDate: string | null;
  tags: string[];
}

export type FilterOptions = {
  search: string;
  priority: string;
  completed: string;
  tags: string[];
};

function App() {
  const [todos, setTodos] = useState<Todo[]>(() => {
    const savedTodos = localStorage.getItem("todos");
    return savedTodos ? JSON.parse(savedTodos) : [];
  });

  const [filters, setFilters] = useState<FilterOptions>({
    search: "",
    priority: "all",
    completed: "all",
    tags: [],
  });

  const [darkMode, setDarkMode] = useState(() => {
    const saved = localStorage.getItem("darkMode");
    return saved ? JSON.parse(saved) : false;
  });

  useEffect(() => {
    localStorage.setItem("todos", JSON.stringify(todos));
  }, [todos]);

  useEffect(() => {
    localStorage.setItem("darkMode", JSON.stringify(darkMode));
  }, [darkMode]);

  const addTodo = (
    text: string,
    priority: "low" | "medium" | "high",
    dueDate: string | null,
    tags: string[]
  ) => {
    if (text.trim()) {
      setTodos([
        ...todos,
        {
          id: Date.now(),
          text: text.trim(),
          completed: false,
          priority,
          dueDate,
          tags,
        },
      ]);
    }
  };

  const toggleTodo = (id: number) => {
    setTodos(
      todos.map((todo) =>
        todo.id === id ? { ...todo, completed: !todo.completed } : todo
      )
    );
  };

  const deleteTodo = (id: number) => {
    setTodos(todos.filter((todo) => todo.id !== id));
  };

  const handleDragEnd = (result: DropResult) => {
    if (!result.destination) return;

    const items = Array.from(todos);
    const [reorderedItem] = items.splice(result.source.index, 1);
    items.splice(result.destination.index, 0, reorderedItem);

    setTodos(items);
  };

  const filteredTodos = todos.filter((todo) => {
    const matchesSearch = todo.text
      .toLowerCase()
      .includes(filters.search.toLowerCase());
    const matchesPriority =
      filters.priority === "all" || todo.priority === filters.priority;
    const matchesCompleted =
      filters.completed === "all" ||
      (filters.completed === "completed" ? todo.completed : !todo.completed);
    const matchesTags =
      filters.tags.length === 0 ||
      filters.tags.some((tag) => todo.tags.includes(tag));

    return matchesSearch && matchesPriority && matchesCompleted && matchesTags;
  });

  return (
    <ConfigProvider
      theme={{
        algorithm: darkMode
          ? antdTheme.darkAlgorithm
          : antdTheme.defaultAlgorithm,
      }}
      locale={require("antd/locale/zh_CN").default}
    >
      <div className={`app${darkMode ? " dark" : ""}`}>
        <div className="app-container">
          <header className="app-header">
            <h1>待办清单</h1>
            <ThemeToggle
              darkMode={darkMode}
              onToggle={() => setDarkMode((d: boolean) => !d)}
            />
          </header>
          <TodoForm onAdd={addTodo} />
          <TodoFilter
            filters={filters}
            onFilterChange={setFilters}
            todos={todos}
          />
          <DragDropContext onDragEnd={handleDragEnd}>
            <TodoList
              todos={filteredTodos}
              onToggle={toggleTodo}
              onDelete={deleteTodo}
            />
          </DragDropContext>
        </div>
      </div>
    </ConfigProvider>
  );
}

export default App;
